package com.itheima.service;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {

    SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /*查询所有*/
    public List<Brand> selectAll(){
     //调用BrandMapper.selectAll()
        //2.获取对应的sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取对应的BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        List<Brand> brands = mapper.selectAll();
        sqlSession.close();

        return brands;
    }
    /*根据id查询*/
    public Brand selectById(int id ){
        //调用BrandMapper.selectById()

        //2.获取对应的sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取对应的BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        Brand brand = mapper.selectById(id);

        sqlSession.close();

        return brand;
    }
    //增删改方法要提交事务
    //添加
    public  void add(Brand brand){
        //2.获取对应的sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取对应的BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        mapper.add(brand);

        //提交事务
        sqlSession.commit();

        //释放资源
        sqlSession.close();

    }

    /*根据id修改*/
    public void update(Brand brand ){
        //调用BrandMapper.update()

        //2.获取对应的sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取对应的BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        mapper.update(brand);

        //提交事务
        sqlSession.commit();

        //释放资源
        sqlSession.close();

    }
    /*根据id删除*/
    public void delete(int id ){
        //调用BrandMapper.update()

        //2.获取对应的sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3.获取对应的BrandMapper
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //4.调用方法
        mapper.delete(id);

        //提交事务
        sqlSession.commit();

        //释放资源
        sqlSession.close();

    }

}
